import { useUserStore } from '@/stores/userdata'
import { ref } from 'vue'

export const usePayment = () => {
  const loading = ref(false)
const useStore=useUserStore()

  // 检查用户登录和手机号绑定状态
  // const checkUserAuth = async () => {
  //   if (!useStore.isLoggedIn || !useStore.userData?.phone) {
  //     uni.showModal({
  //       title: '提示',
  //       content: '请先登录并绑定手机号',
  //       confirmText: '去登录',
  //       success: (res) => {
  //         if (res.confirm) {
  //           uni.switchTab({ url: '/views/my/index' })
  //         }
  //       }
  //     })
  //     return false
  //   }
  //   return true
  // }

  // 检查未支付订单
  const checkUnpaidOrder = async (productId: number) => {
    try {
      const { data } = await uni.request({
        url: 'https://37ace603.r34.cpolar.top/orders',
        method: 'GET',
        data: { status: 'pending' },
        header: {
          'Authorization': `Bearer ${useStore.token}`
        }
      })
      return Array.isArray(data) ? data.find(order => order.product_id === productId) : null
    } catch (error) {
      console.error('检查未支付订单失败:', error)
      return null
    }
  }

  // 查询订单状态
  const checkOrderStatus = async (orderId: string): Promise<boolean> => {
    try {
      const { data } = await uni.request({
        url: `https://37ace603.r34.cpolar.top/orders/${orderId}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${useStore.token}`
        }
      })
      // data?.status === 'paid'
      return true
    } catch (error) {
      console.error('查询订单状态失败:', error)
      return false
    }
  }

  // 创建用户产品记录
  const createUserProduct = async (productId: number) => {
    try {
      await uni.request({
        url: 'https://37ace603.r34.cpolar.top/userproducts',
        method: 'POST',
        data: {
          product_id: productId,
          phone: useStore.userData?.phone
        },
        header: {
          'Authorization': `Bearer ${useStore.token}`
        }
      })
      return true
    } catch (error) {
      console.error('创建用户产品记录失败:', error)
      return false
    }
  }

  // 处理支付流程
  const handlePayment = async (productId: number) => {
    if (!productId || typeof productId !== 'number' || productId < 1) {
      uni.showToast({ title: '无效的商品ID', icon: 'none' })
      return false
    }

    loading.value = true

    try {
      // // 1. 检查用户授权
      // if (!await checkUserAuth()) {
      //   return false
      // }

      // 2. 创建支付订单
      const rul = await uni.request({
        url: 'https://37ace603.r34.cpolar.top/payments',
        method: 'POST',
        data: {
          product_id: productId,
          phone: useStore.userData?.phone,
          openid: useStore.userData?.openid
        },
        header: {
          'Authorization': `Bearer ${useStore.token}`,
          'Content-Type': 'application/json'
        }
      })
      console.log('rul',rul)

      // if (!paymentResponse?.payment_params) {
      //   throw new Error('支付参数缺失')
      // }

      // 3. 发起支付
      try {
        // await uni.requestPayment({
        //   // ...paymentResponse.payment_params,
        //   provider: 'wxpay'
        // })

        // 4. 轮询订单状态
        let isPaid = false
        let retryCount = 0
        const maxRetries = 3
        const retryDelay = 1000

        // uni.showLoading({ title: '确认订单中...' })

        // while (retryCount < maxRetries && !isPaid) {
        //   isPaid = await checkOrderStatus(paymentResponse.order_id)
        //   if (isPaid) break
          
        //   if (retryCount < maxRetries - 1) {
        //     await new Promise(resolve => setTimeout(resolve, retryDelay))
        //   }
        //   retryCount++
        // }

        if (!isPaid) {
          throw new Error('订单支付未确认')
        }

        // 5. 支付成功处理
        await createUserProduct(productId)
        // await productStore.refreshProducts()

        uni.showToast({ title: '支付成功', icon: 'success' })
        
        // 6. 如果需要跳转到商品页面
        // const product = productStore.getProductById(productId)
        // if (product?.click_url) {
        //   setTimeout(() => {
        //     uni.navigateTo({
        //       url: `/pages/webview/webview?url=${encodeURIComponent(product.click_url)}`
        //     })
        //   }, 1500)
        // }

        return true
      } catch (error: any) {
        if (error.errMsg?.includes('requestPayment:fail cancel')) {
          uni.showToast({ title: '支付已取消', icon: 'none' })
        } else {
          throw error
        }
      }
    } catch (error: any) {
      console.error('支付流程错误:', error)
      let errorMsg = '支付失败，请重试'

      if (error.message?.includes('支付参数缺失')) {
        errorMsg = '支付参数错误，请联系客服'
      } else if (error.response?.status === 401) {
        errorMsg = '登录已过期，请重新登录'
        useStore.reset()
        uni.navigateTo({ url: '/views/my/index' })
      }

      uni.showToast({ title: errorMsg, icon: 'none' })
      return false
    } finally {
      loading.value = false
      uni.hideLoading()
    }
  }

  return {
    loading,
    handlePayment
  }
}